package hostmgr

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"youbei/dao"
	conf "youbei/utils/config"

	"github.com/segmentio/ksuid"

	"github.com/beego/beego/httplib"
)

// 请求API并处理响应的帮助函数
func requestAPI(url string, request interface{}, response *dao.Response) error {
	requestBytes, err := json.Marshal(request)
	if err != nil {
		return err
	}

	if err := httplib.Post(url).Header("Content-Type", "application/json").Body(requestBytes).ToJSON(response); err != nil {
		return err
	}

	if response.Status != 200 {
		return errors.New(response.Msg)
	}

	return nil
}

// AddhostServer 作用是让模块1（server）添加模块2（client），参数是模块2的信息
func AddhostServer(host *dao.Host) error {
	config, err := conf.LoadConfigFromFile()
	if err != nil {
		return err
	}

	baseUrl := fmt.Sprintf("http://%s:%s/client", host.HostAddr, host.Port)

	// 1. 向模块2的第一个接口发送数据
	stepOneResponse := dao.Response{}
	stepOneRequest := dao.Request{Uuid: config.ConfServer.Uuid, Msg: strconv.Itoa(config.ConfServer.Port)}
	if err := requestAPI(baseUrl+"/stepone", stepOneRequest, &stepOneResponse); err != nil {
		return err
	}
	host.HostUuid = stepOneResponse.Msg

	// 2. 生成Token，然后发送给模块2
	host.Token = ksuid.New().String()
	stepTwoRequest := dao.Request{Uuid: config.ConfServer.Uuid, Msg: host.Token}
	stepTwoResponse := dao.Response{}
	if err := requestAPI(baseUrl+"/steptwo", stepTwoRequest, &stepTwoResponse); err != nil {
		return err
	}

	return nil
}
